import { BrowserWindow, ipcMain, IpcMainEvent } from 'electron';
import path from 'path';
import { PictureFolder } from '../entities';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const glob = require('glob');

export class IPC {
  public win: BrowserWindow;

  constructor(win: BrowserWindow) {
    this.win = win;
    this.on();
  }

  protected on(): void {
    ipcMain.on('min', () => this.win.minimize());
    ipcMain.on('max', () => {
      if (this.win.isMaximized()) {
        this.win.unmaximize();
      } else {
        this.win.maximize();
      }
    });
    ipcMain.on('close', () => this.win.close());

    ipcMain.on('read-picture-folders', (evt: IpcMainEvent, folder: string) => {
      const pattern = path.normalize(`${folder}/**/*.jpg`).replace(/\\/g, '/');
      const files: string[] = glob.sync(pattern);
      const map = new Map<string, string[]>();
      files.forEach((filePath: string) => {
        const dirname = path.dirname(filePath);
        if (!map.has(dirname)) {
          map.set(dirname, []);
        }
        const arr = map.get(dirname);
        if (arr) {
          arr.push(filePath);
        }
      });
      const folders: PictureFolder[] = [];
      map.forEach((items, key) => {
        folders.push(new PictureFolder(key, items));
      });
      evt.returnValue = folders;
    });
  }
}
